//
//  TextViewWithRequiredView.swift
//  ezyform
//
//  Created by Moennig Q on 4/9/2022.
//  Copyright © 2022 Client.Solution Pty Ltd. All rights reserved.
//
import UIKit
import RxGesture
import RxCocoa
import RxSwift
enum TextfieldContentType: Int{
    case text = 0//一般的文本而已
    case positiveNumber//正整数校验
    case positiveNumber3//三位正整数校验，1到999
    case phone//10位
    case email
    case nmi
    case postCode
    case password
    case text250
    case username
    case abn
    case unitPrice
    
}
enum TextFieldValidStatus: Int {
    case valid = 0//验证通过
    case invalid = 1//验证不通过
    case validing = 2//正在验证中
}
class TextFieldWithRequiredView: UIView {
    lazy var disposeBag = DisposeBag()
    private var contentType: TextfieldContentType = .text
    var editingDidEndClosure: ((String)->Void)?//编辑完成业务逻辑需要处理的回调
    var editingChangedClosure: ((String)->Void)?//编辑完成业务逻辑需要处理的回调
    var validStatus: BehaviorRelay<TextFieldValidStatus> = BehaviorRelay.init(value: TextFieldValidStatus.invalid)
    var needCheckFlag: Bool = true//true表示需要检验
    var defaultTipMsg: String = R.string.localizable.thisIsRequired() //校验内容为空时，定制的提示语,默认是this is required
    
    lazy var textField: DIYTextField = {
        let textField = DIYTextField()
        return textField
    }()
    lazy var requiredLabel: BaseLabel = {
        return ViewFactory.shared.generateRequiredLabel()
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setUpView()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    init(_ type: TextfieldContentType = .text) {
        super.init(frame: CGRect.zero)
        self.contentType = type
        self.setUpView()
        
    }
    private func setUpView(){
        self.addSubview(textField)
        textField.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(DIYTextField.height)
        }
        //required label
        self.addSubview(requiredLabel)
        requiredLabel.snp.makeConstraints { make in
            make.top.equalTo(textField.snp.bottom).offset(2)
            make.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
            make.bottom.equalToSuperview()
        }
        if self.contentType == .phone || self.contentType == .positiveNumber || self.contentType == .positiveNumber3{
            textField.keyboardType = .numberPad//标准电话键盘，支持＋＊＃字符
        }else if self.contentType == .unitPrice {
            textField.keyboardType = .decimalPad//A number pad with a decimal point
        }else if self.contentType == .email {
            textField.keyboardType = .emailAddress
        }else{
            textField.keyboardType = .default
        }
        //
        if self.needCheckFlag {
            self.validStatus.accept(.invalid)
        }else{
            self.validStatus.accept(.valid)
        }
        //数据绑定
        self.initBinding()
    }
    private func initBinding(){
        //监听输入的内容是否符合校验,只能输入数字
        textField.rx.controlEvent(.editingChanged).asObservable().subscribe(onNext: {[weak self]  in
            guard let strongSelf = self else {return}
            var content = strongSelf.textField.text ?? ""
            if content.count > 0{
                if strongSelf.contentType == .positiveNumber{
                    let money = NSPredicate(format: "SELF MATCHES %@", "^[1-9][0-9]*$")
                    if money.evaluate(with: content) == false{//校验
                        strongSelf.textField.text = String(content.prefix(content.count - 1))
                    }
                }else if strongSelf.contentType == .positiveNumber3{
                    if let data = Int(content), data > 0 && data < 1000 {
                        
                    }else{
                        content = String(content.prefix(content.count - 1))
                        strongSelf.textField.text = content
                    }
                    
                }else if strongSelf.contentType == .text250{
                    if Tool().isValidLength(content: content) == false{
                        strongSelf.textField.text = String(content.prefix(content.count - 1))
                    }
                }else if strongSelf.contentType == .username{
                    if Tool().isValidUserName(content: content) == false{
                        strongSelf.textField.text = String(content.prefix(content.count - 1))
                        strongSelf.showInvalidMsg(R.string.localizable.theFieldCanOnlyInputLettersAnd())
                    }else{
                        strongSelf.hideInvalidMsg()
                    }
                }else if strongSelf.contentType == .phone {
                    let firstChar = String(content.prefix(1))
                    if firstChar != "0" || content.count > 10{//以0开头，10电话号码
                        strongSelf.textField.text = String(content.prefix(content.count - 1))
                        strongSelf.showInvalidMsg(R.string.localizable.mustBe10DigitNumberEg0412345678())
                    }else {
                        strongSelf.hideInvalidMsg()
                    }
                }else if strongSelf.contentType == .password{//密码不能输入空格
                    let lastChar =  String(content.suffix(1))
                    if lastChar == " " {
                        strongSelf.textField.text = String(content.prefix(content.count - 1))
                    }
                }else if strongSelf.contentType == .unitPrice{
                    if Tool().isValidUnitPrice(content) == false{
                        if let doubleValue = Double(content){
                            let splitList = content.split(separator: ".")
                            if doubleValue > 99.99{
                                if splitList.count > 0{
                                    strongSelf.textField.text =  String(splitList[0].prefix(2)) + (splitList.count > 1 ? ("." + splitList[1]) : "")
                                }
                            }else if splitList[0].count > 2{
                                strongSelf.textField.text =  String(splitList[0].suffix(splitList[0].count - 1)) + "." + splitList[1]
                            }else{
                                strongSelf.textField.text =  String(content.prefix(content.count - 1))
                            }
                        }else{
                            let realContent = content.filter({"0123456789.".contains($0)})//删除字符串中的非数字
                            strongSelf.textField.text =  realContent
                        }
                    }
                }
            }
            strongSelf.editingChangedClosure?(content)
        }).disposed(by: self.disposeBag)
        //监听文本编辑完成在校验信息，控制是否显示提示信息
        textField.rx.controlEvent([.editingDidEnd]).asObservable().subscribe(onNext: {[weak self]  in
            guard let strongSelf = self else {return}
            strongSelf.checkTextIfValid()
        }).disposed(by: self.disposeBag)
        //监听键盘的Return，关闭键盘且触发editingDidEnd
        textField.rx.controlEvent([.editingDidEndOnExit]).asObservable().subscribe(onNext: {[weak self]  in
            guard let strongSelf = self else {return}
            strongSelf.textField.resignFirstResponder()
        }).disposed(by: self.disposeBag)
    }
    //MARK: - 改变必填项needCheckFlag,例如：从必填项改成非必填项， 从非必填改成必填，注册界面accreditedNumber
    func changeCheckFlag(_ flag: Bool){
        self.needCheckFlag = flag
        self.checkTextIfValid()
    }
    //MARK: - 检查必填项的是否符合一般规则校验
    func checkIfStandardValid(){
        self.hideInvalidMsg()
        //不需要校验时，隐藏
        if self.needCheckFlag == false{
            self.validStatus.accept(.valid)
            return
        }
        let content = (textField.text ?? "").trimmingCharacters(in: .whitespaces)
        if content == ""{//一般的文本
            self.showInvalidMsg(self.defaultTipMsg)
        }else {
            //1.phone无效
            if contentType == .phone {//10校验
                if Tool().isValidPhone(phone: content) == false{
                    self.showInvalidMsg(R.string.localizable.mustBe10DigitNumberEg0412345678())
                }
            }else if contentType == .email {//2.邮件格式无效
                if !Tool().isValidEmail(emailStr: content){//email格式无效
                    self.showInvalidMsg(R.string.localizable.pleaseEnterAValidEmailAddress())
                }
            }else if contentType == .nmi{
                if Tool().isValidNMI(nmi: content) == false{//nmi格式无效
                    self.showInvalidMsg(R.string.localizable.nmiMustBe10To11Digits())
                }
            }else if contentType == .postCode{
                if Tool().isValidPostcode(postcode: content) == false{//nmi格式有效
                    self.showInvalidMsg(R.string.localizable.postcodeMustBe4Digits())
                }
            }else if contentType == .password{
                if Tool().isValidPwd(pwd: content) == false{//nmi格式无效
                    self.showInvalidMsg(R.string.localizable.yourPasswordMustBe620Characters())
                }
            }else if contentType == .abn{
                if Tool().isValidABN(abn: content) == false{//abn格式无效
                    self.showInvalidMsg(R.string.localizable.abnShouldBeAn11DigitNumber())
                }
            }
        }
    }
    
    
    //MARK: - 隐藏tip  msg
    func hideInvalidMsg(){
        self.textField.layer.borderColor = UIColor(hexStr: "#292D3233").cgColor
        self.requiredLabel.text = ""
        self.validStatus.accept(.valid)//校验合法
    }
    //MARK: - 显示msg
    func showInvalidMsg(_ msg: String){
        self.textField.layer.borderColor = UIColor(hexStr: "#ED3E3EFF").cgColor
        self.requiredLabel.text = msg
        self.validStatus.accept(.invalid)//校验不合法，
    }
    //
    func checkTextIfValid(){
        //1.验证是否符合基本规则
        self.checkIfStandardValid()
        //2.处理个性规则
        let data = (self.textField.text ?? "").trimmingCharacters(in: .whitespaces)
        self.editingDidEndClosure?(data)
    }
}
